from django.shortcuts import render
from apps.news.models import News,NewsCategory
from django.conf import settings
from utils import restful
from .serializers import NewsSerializer,CommentSerializer
from django.http import Http404
from .forms import PublicCommentForm
from .models import Comment,Banner
from apps.xfzauth.decorators import xfz_login_requrie
from django.db.models import Q

def index(request):
    count = settings.ONE_PATE_NEWS_COUNT
    # 根据时间先后顺序来提取出数据给前端，然后按切片来控制显示条数
    newses = News.objects.select_related('category','author').order_by('-pub_time')[0:count]
    categories = NewsCategory.objects.all()
    context = {
        'newses':newses,
        'categories':categories,
        'banners':Banner.objects.all()
    }
    return render(request,'news/index.html',context=context)

def news_list(request):
    # 获取前端传来的p，通过p参数来指定获取到第几页数据
    # 这个参数是通过查询字符串的方式传过来的，如news/list/?p=2
    # 为了能让字符串的p能运算，所有转换成整型,并且如果没传，默认设置为1
    page = int(request.GET.get("p",1))
    # 获取前端传来的分类ID
    category_id = int(request.GET.get('category_id',0))
    start = (page-1)*settings.ONE_PATE_NEWS_COUNT
    end = start+settings.ONE_PATE_NEWS_COUNT
    if category_id == 0:
        newses = News.objects.select_related('category','author').all()[start:end]
    else:
        newses = News.objects.select_related('category','author').filter(category_id=category_id)[start:end]
    # ，序列化news，因为newses是个queryset对象，里面有多个数据，所以加上many=True
    serializer = NewsSerializer(newses,many=True)
    data = serializer.data
    return restful.result(data=data)

def news_detail(request,news_id):
    try:
        news = News.objects.select_related('category','author').prefetch_related('comments__author').get(pk=news_id)
        context = {
            'news':news
        }
        return render(request,'news/news_detail.html',context=context)
    except News.DoesNotExist:
        raise Http404

# 发表评论
@xfz_login_requrie
def public_comment(request):
    form = PublicCommentForm(request.POST)
    if form.is_valid():
        news_id = form.cleaned_data.get('news_id')
        content = form.cleaned_data.get('content')
        news = News.objects.get(pk=news_id)
        comment = Comment.objects.create(content=content,news=news,author=request.user)
        # 序列化评论comment，因为上面的comment不是queryset对象，所以不用加上many=True
        serializer = CommentSerializer(comment)
        return restful.result(data=serializer.data)
    else:
        return restful.params_error(message=form.get_errors())


def search(request):
    q = request.GET.get('q')
    context = {}
    if q:
        # 搜索标题包含q和内容包含q
        newses = News.objects.filter(Q(title__icontains=q)|Q(content__icontains=q))
        context['newses'] = newses
    return render(request,'search/search_index.html',context=context)

